<template>
  <div id="myshare">
    <!-- 操作按钮 -->
    <el-row :gutter="20" style="margin-bottom: 20px;">
      <el-col :span="8">
        <el-input v-model="searchQuery" placeholder="请输入分享ID" clearable>
          <template #prefix>
            <i class="el-icon-search"></i>
          </template>
        </el-input>
      </el-col>

      <el-col :span="16" style="text-align: left;">
        <el-button type="primary" @click="handleSearch">搜索</el-button>
        <el-button type="danger" :disabled="selectedRows.length === 0" @click="handleDelete">删除</el-button>
        <el-button type="success" @click="openModifyDialog">修改过期时间</el-button>
      </el-col>
    </el-row>

    <!-- 文件列表 -->
    <el-table :data="filteredTableData" style="width: 100%" @selection-change="handleSelectionChange">
      <!-- 多选框 -->
      <el-table-column type="selection" width="55"></el-table-column>

      <!-- 分享ID -->
      <el-table-column label="分享ID" width="200">
        <template v-slot="scope">
          <span>{{ scope.row.shareId }}</span>
        </template>
      </el-table-column>

      <!-- 分享链接 -->
      <el-table-column label="分享链接" width="350">
        <template v-slot="scope">
          <el-input v-model="scope.row.shareLink" readonly>
            <template #append>
              <el-button @click="copyLink(scope.row.shareLink)">复制链接</el-button>
            </template>
          </el-input>
        </template>
      </el-table-column>

      <!-- 创建时间 -->
      <el-table-column label="创建时间" width="200">
        <template #default="scope">
          <span>{{ formatTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>

      <!-- 更新时间 -->
      <el-table-column label="更新时间" width="200">
        <template #default="scope">
          <span>{{ formatTime(scope.row.updateTime) }}</span>
        </template>
      </el-table-column>

      <!-- 过期时间 -->
      <el-table-column label="过期时间" width="200">
        <template #default="scope">
          <span>{{ calculateExpiration(scope.row.expireTime) }}</span>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog title="修改过期时间" v-model="modifyDialogVisible" width="450px" class="modify-dialog">
      <el-form :model="modifyForm" label-width="120px">
        <el-form-item label="分享ID">
          <el-input v-model="modifyForm.shareId" readonly></el-input>
        </el-form-item>
        <el-form-item label="过期时间（天）">
          <el-input v-model="modifyForm.expireTime" type="number" placeholder="请输入新的过期时间" min="1">
          </el-input>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer" style="text-align: right; padding: 10px 20px;">
        <el-button type="danger" @click="modifyDialogVisible = false">取消</el-button>
        <el-button type="primary" :disabled="!modifyForm.expireTime || modifyForm.expireTime <= 0"
          @click="handleModifySubmit">
          确定
        </el-button>
      </div>
    </el-dialog>

    <!-- 分页组件 -->
    <el-pagination background layout="total, sizes, prev, pager, next, jumper" :total="total"
      :current-page="queryParams.pageNum" :page-sizes="[1, 5, 10]" :page-size="queryParams.pageSize"
      @size-change="handleSizeChange" @current-change="handlePageChange" />
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import axios from "@/utils/request.js";  // Import the custom axios instance
import dayjs from "dayjs";

// 从 localStorage 中获取 token 并解析 userId
const token = localStorage.getItem("token");
let userId = 0;

// 假设解析 token 的逻辑
if (token) {
  try {
    const parsedToken = JSON.parse(atob(token.split(".")[1])); // 假设 token 是 JWT 格式
    userId = parsedToken.userId || 0;
  } catch (error) {
    console.error("Token 解析失败:", error);
    userId = 1; // 如果解析失败，设置为 0 或其他默认值
  }
} else {
  userId = 11; // 假设没有 token，手动设置一个假 userId
}


// 响应式数据
const tableData = ref([]);
const searchQuery = ref("");
const selectedRows = ref([]);
const total = ref(0);

// 过滤后的数据
const filteredTableData = computed(() => {
  return tableData.value.filter((row) => {
    const shareId = String(row.shareId || "");
    const fileName = String(row.fileName || "");
    return shareId.includes(searchQuery.value) || fileName.includes(searchQuery.value);
  });
});

// 格式化时间
const formatTime = (time) => {
  if (!time) return "无";
  return dayjs(time).format("YYYY-MM-DD HH:mm:ss");
};

// 计算过期天数
const calculateExpiration = (expireTime) => {
  return expireTime <= 0 ? "已过期" : `剩余 ${expireTime} 天`;
};

// 分页
const queryParams = ref({
  pageNum: 1,
  pageSize: 5,
});

const handleSizeChange = (newPageSize) => {
  queryParams.value.pageSize = newPageSize;
  fetchTableData();
};

const handlePageChange = (newPageNum) => {
  queryParams.value.pageNum = newPageNum;
  fetchTableData();
};

// 加载数据
const fetchTableData = async () => {
  try {
    const response = await axios.get("/file/list", {
      params: {
        userId,
        query: searchQuery.value || "",
        pageNumber: queryParams.value.pageNum,
        pageSize: queryParams.value.pageSize,
      },
    });
    const data = response.data;
    tableData.value = data.records.map((row) => ({
      shareId: row.shareId || "",
      fileName: row.fileName || "",
      shareLink: row.shareLink || "无",
      createTime: row.createTime || null,
      updateTime: row.updateTime || null,
      expireTime: row.expireTime || 0,
    }));
    total.value = data.total || 0;
    ElMessage.success("数据加载完成");
  } catch (error) {
    console.error("数据加载失败:", error);
    ElMessage.error("无法加载数据，请稍后重试");
  }
};

// 页面加载时获取数据
onMounted(() => {
  fetchTableData();
});

// 操作方法
const handleSearch = () => {
  queryParams.value.pageNum = 1; // 重置到第一页
  fetchTableData();
};

const handleDelete = async () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning("请先选择要删除的链接");
    return;
  }

  ElMessageBox.confirm("确定要删除选中的链接吗？", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      try {
        const promises = selectedRows.value.map((row) =>
          axios.put("/file/status", null, {
            params: { share_id: row.shareId },
          })
        );

        const responses = await Promise.all(promises);

        // 修改为检查每个响应的 code 是否为 200
        const allSuccess = responses.every(
          (response) => response.code === 200 // 只检查 response.code 而不是 response.status
        );

        if (allSuccess) {
          ElMessage.success("删除成功");
          fetchTableData();
        } else {
          ElMessage.error("部分链接删除失败，请稍后重试");
        }
      } catch (error) {
        console.error("删除失败:", error);
        ElMessage.error("删除失败，请检查网络或后端服务");
      }
    })
    .catch(() => {
      ElMessage.info("已取消删除");
    });
};


// 修改对话框数据
const modifyForm = ref({
  shareId: "",
  expireTime: 0,
});

const modifyDialogVisible = ref(false);

const openModifyDialog = () => {
  if (selectedRows.value.length !== 1) {
    ElMessage.warning("请选择一个链接进行修改");
    return;
  }

  const row = selectedRows.value[0];
  modifyForm.value.shareId = row.shareId;
  modifyForm.value.expireTime = row.expireTime;
  modifyDialogVisible.value = true;
};

const handleModifySubmit = async () => {
  try {
    const { shareId, expireTime } = modifyForm.value;

    if (!Number.isInteger(+expireTime) || +expireTime <= 0) {
      ElMessage.warning("过期时间必须为大于 0 的整数");
      return;
    }

    const response = await axios.put("/file/update", null, {
      params: {
        share_id: shareId,
        expire_time: parseInt(expireTime, 10),
      },
    });

    console.log(response);
    if (response.status === 200 || response.code === 200) {
      ElMessage.success(response.msg || "过期时间更新成功");
      modifyDialogVisible.value = false;
      fetchTableData();
    } else {
      ElMessage.error(response.msg || "更新失败，请稍后重试");
    }

  } catch (error) {
    console.error("更新失败:", error);
    ElMessage.error(error.response?.data?.message || "网络错误，请检查后端服务是否正常");
  }
};

const handleSelectionChange = (rows) => {
  selectedRows.value = rows;
};

const copyLink = (link) => {
  navigator.clipboard.writeText(link).then(() => {
    ElMessage.success("链接已复制到剪贴板");
  });
};
</script>


<style scoped>
.modify-dialog {
  min-height: 200px;
  padding: 20px;
}
</style>
